<template>
<div class="background">
  <p class="font animated bounceInDown" >答题对战</p>
  <p class="font0  animated bounceIn">Question Match</p>
  <p class="font1  animated bounceIn">让兴趣不再孤单</p>
  <P class="font2  animated bounceIn">让爱好不再流浪</P>
  <button  @getuserinfo="getVxUserInfo" open-type="getUserInfo" class="btn" style="vertical-align:middle;letter-spacing:5px"><span>立即进入</span></button>
  
  <div class="weui-footer weui-footer_fixed-bottom">   
    <div class="weui-footer__text">
      <br>
      <progress :percent="percent" show-info active-mode="forwards" active="true" stroke-width="12"/>
      <p>{{msg}}</p>
    </div>
  </div>
</div>
</template>

<script>
import store from '../../utils/store'
import httpkit from '../../utils/http-kit'
const appId = 'wx08c3d67308581385' // 开发者appid
const secret = 'd59af2b0d8d4c09ed7ed2685e21b16fd'
export default {
  onLoad () { // 清空数据重新加载
    Object.assign(this.$data, this.$options.data())
  },
  mounted () {
    var scene = wx.getLaunchOptionsSync()
    // 根据场景值选择跳转页面
    console.log(scene)
    console.log(scene.scene)
    if (scene.scene === 1008 || scene.scene === 1007) {
      console.log(scene.query)
      this.isForword = true
      store.commit('changeRoomid', scene.query.roomId)
      store.commit('changeRivalid', scene.query.rivalId)
    }
  },
  data () {
    return {
      openid: '',
      session_key: '',
      iflogin: true,
      connectedMqtt: false,
      connectedServer: false,
      msg: '',
      percent: 0,
      isForword: false
    }
  },
  components: {},
  methods: {
    // 根据URL跳转界面 url string 界面的URl
    goTo (url) {
      console.log('跳转到主页')
      wx.redirectTo({
        url: url
      })
    },
    // 获取用户信息
    getVxUserInfo (e) {
      if (e.target.userInfo) {
        this.isLogin()
      }
    },
    // 登录
    isLogin () {
      // wx.showLoading({ title: '加载中' })
      var _this = this

      wx.getSetting({// 调用微信授权接口
        success (res) {
          if (!res.authSetting['scope.userInfo']) { // 未授权getUserInfo
            wx.authorize({
              scope: 'scope.getUserInfo',
              success (res) {
                // 用户已经同意小程序使用用户信息，后续调用 wx.userInfo 接口不会弹窗询问
                console.log(res)
                console.log('用户同意授权')
              },
              fail (err) {
                console.log(err)
                console.log('用户未授权')
                _this.msg = '用户未授权'
              }
            })
          } else { // 已授权
            wx.getUserInfo({
              success (res) {
                _this.percent = 20
                console.log('用户已授权，正在读取用户信息')
                _this.msg = '用户已授权，正在读取用户信息'
                _this.loginOk(res)
              },
              fail (err) {
                console.log(err)
              }
            })
          }
        }
      })
    },
    loginOk (res) { // 登录成功后的信息处理
      let _this = this
      store.commit('changeUserInfo', res.userInfo)
      _this.getOpenId()
      _this.msg = '获取code，正在请求open_id和session_key'
      _this.percent = 40
    },
    getOpenId () { // 获取用户的openid
      var _this = this
      wx.login({
        success (res) {
          if (res.code) { // 发起网络请求
            wx.request({
              url: 'https://api.weixin.qq.com/sns/jscode2session',
              data: {
                appid: appId, // 开发者appid
                secret: secret, // 开发者AppSecret(小程序密钥)
                grant_type: 'authorization_code', // 默认authorization_code
                js_code: res.code // wx.login登录获取的code值
              },
              success (res) { // 储存用户相关信息
                store.commit('changeOpenid', res.data.openid)
                console.log(res.data.openid)
                store.commit('changeSession_key', res.data.session_key)
                console.log('获得open_id和session_key')
                _this.percent = 60
                httpkit.get('/user/login', { // 调用后端登录接口
                  wechatId: res.data.openid,
                  nickname: store.state.userInfo.nickName,
                  avatarUrl: store.state.userInfo.avatarUrl,
                  sessionKey: store.state.session_key
                }).then(res => {
                  store.commit('changeUserid', res.data.id)
                  store.commit('changeScore', res.data.score)
                  store.commit('changeToken', res.data.token)
                  console.log('连接服务器成功')
                  _this.msg = '连接服务器成功'
                  console.log(store.state.userInfo)
                  _this.percent = 80
                  _this.connectedServer = true
                  // if (store.state.client == null) { // 连接MQTT服务器
                  var mqtt = require('mqtt')
                  var client = mqtt.connect(process.env.MQTT_API, {
                    clientId: 'mqttjs_' + store.state.openid + Math.round(Math.random() * 255),
                    protocolId: 'MQTT',
                    CleanSession: true,
                    useSSL: false,
                    username: 'mqtttest',
                    password: 'scau',
                    keepalive: 3000
                  })

                  client.on('error', (error) => {
                    console.log('连接失败:', error)
                    client.end()
                    wx.showModal({
                      title: 'error',
                      content: '与mqtt服务器断开连接',
                      showCancel: false,
                      confirmText: '重新登录',
                      success (res) {
                        if (res.confirm) {
                          console.log('用户点击确定')
                          _this.goTo('../login/main')
                        }
                      }
                    })
                  })

                  client.on('connect', function () {
                    _this.connectedMqtt = true
                    _this.percent = 100
                    store.commit('changeClient', client)
                    console.log('连接MQTT服务器成功')
                    _this.msg = '连接MQTT服务器成功'

                    client.subscribe('/public/TEST/' + store.state.openid, function (err) {
                      if (!err) {
                        console.log('订阅完成')
                        if (!_this.isForword) {
                          _this.goTo('../index/main')
                        } else { // 请求房间信息
                          // debugger
                          httpkit.get('/match/join', {
                            id: store.state.userid,
                            friendId: store.state.rivalid,
                            roomId: store.state.roomid
                          }).then(res => {
                            // debugger
                            if (res.data !== null) {
                              store.commit('changeRivalInfo', res.data)
                              _this.goTo('../room/main')
                            } else {
                              _this.goTo('../index/main')
                            }
                          })
                        }
                      } else {
                        console.log('连接服务器失败' + err)
                      }

                      client.on('reconnect', (error) => {
                        console.log('正在重连:', error)
                        client.end()
                        wx.redirectTo({
                          url: '../login/main'
                        })
                        // client.end()
                      })
                    })
                  })

                  client.on('message', function (topic, message) {
                    console.log(JSON.parse(message))
                    switch (JSON.parse(message).type) {
                      case 'subject' : {
                        store.commit('changeSubject', JSON.parse(message))
                        break
                      }
                      case 'Pvp' : {
                        console.log('房间号:' + JSON.parse(message).roomId)
                        store.commit('changeRoomid', JSON.parse(message).roomId)
                        store.commit('changeRivalInfo', JSON.parse(message).user)
                        wx.redirectTo({
                          url: '../prepare/main'
                        })
                        break
                      }
                      case 'FriendsApply': {
                        store.commit('addFriendsApply', JSON.parse(message))
                        break
                      }
                    }
                  })
                  // }
                })
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }

  }
}
</script>
<style lang='scss' scoped>
  @import "./style";
.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}
.background {
  display: flex;
  flex-direction: column;
  background-image: url(https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3059856828,1415522416&fm=26&gp=0.jpg);
  position: absolute;
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.font {
  margin-top: 20%;
  text-align: center;
  font-size: 40px;
  line-height:1.4;
  color: #FFFFFF;
  font-weight:bold;

}
.font0 {
  text-align: center;
  font-size: 20px;
  line-height:1.4;
  color: #FFFFFF;
  letter-spacing:5px;
  font-weight:bold;
}
.font1 {
  margin-top: 70%;
  text-align: center;
  font-size:40rpx;
  line-height:1.4;
  letter-spacing:5px;
  color:aliceblue;
  font-weight:bold;
}
.font2 {
  margin-top: 2%;
  text-align: center;
  font-size:20px;
  line-height:1.4;
  letter-spacing:5px;
  color:aliceblue;
  font-weight:bold;
}
.btn {
  display: inline-block;
  border-radius: 20px;
  background-color: #99b7df;
  border: none;
  color: #FFFFFF;
  text-align: center;
  font-size: 18px;
  height: 7%;
  width: 70%;
  transition: all 0.5s;
  cursor: pointer;
  margin-left: 15%;
  margin-top: 10%;
}
.weui-footer__text {
  font-size: 15px;
  color: rgb(247, 243, 243);
  height: 50px;
}
</style>
